package com.sskj.gocoin.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.method.HideReturnsTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.util.SPUtil;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.NoLoginDialog;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.m.bean.UserInfo;
import com.sskj.gocoin.utils.AsteriskPasswordTransformationMethod;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.ImageUtil;
import com.sskj.gocoin.utils.LanguageUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.PhoneHideUtil;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoin.utils.TipUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.AboutUsActivity;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.gocoin.v.activity.ExchangeActivity;
import com.sskj.gocoin.v.activity.GoogleSettingActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.PayPwdSettingActivity;
import com.sskj.gocoin.v.activity.PersonalActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.activity.SellerApplyActivity;
import com.sskj.gocoin.v.activity.VerifyIdentActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.text.DecimalFormat;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/03/29
 */
@Route(path = RConfig.MINE_FRAGMENT_MAIN)
public class MineFragment extends BaseFragment<MainActivity, MinePresenter> {

    @BindView(R2.id.img_head)
    ImageView imgHead;
    @BindView(R2.id.iv_vip)
    ImageView ivVip;
    //    @BindView(R2.id.notice_img)
//    ImageView noticeImg;
    @BindView(R2.id.tv_account)
    TextView tvAccount;
    @BindView(R2.id.tv_uid)
    TextView tvUid;
    @BindView(R2.id.sign_img)
    TextView signImg;
    @BindView(R2.id.tv_asset)
    TextView tvAsset;
    @BindView(R2.id.tv_asset_cny)
    TextView tvAssetCny;
    //    @BindView(R2.id.notice_switch)
//    TextSwitcher noticeSwitch;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.tv_my_grzl)
    TextView grzlTv;
    @BindView(R2.id.tv_my_aqzx)
    TextView aqzxTv;
    @BindView(R2.id.tv_my_gywm)
    TextView gywmTv;
    @BindView(R2.id.tv_my_sqzss)
    TextView sqzzssTv;
    @BindView(R2.id.tv_my_tbdz)
    TextView tbdzTv;
    @BindView(R2.id.tv_my_wdtg)
    TextView wdtgTv;
    @BindView(R2.id.tv_my_zcgl)
    TextView zcglTv;
    @BindView(R2.id.tv_my_sz)
    TextView szTv;
    @BindView(R2.id.tv_my_sjrz)
    TextView sjrzTv;
    @BindView(R2.id.tv_my_exchange)
    TextView exchangeTv;
    @BindView(R2.id.tv_my_pay_in)
    TextView payInTv;
    @BindView(R2.id.tv_my_pay_out)
    TextView payOutTv;
    @BindView(R2.id.cb_fragment_my_money)
    CheckBox myMoneyCb;
    //    @BindView(R2.id.menu)
//    RecyclerView menuRecyclerView;
//    BaseAdapter<Menu> menuAdapter;
//    List<Menu> menuData = new ArrayList<>();
    private Disposable disposable;
    private AlertDialog shopDialog;

    private UserInfo mUserInfo;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine_c;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void initView() {
        LanguageUtil.changeAppLanguage(getActivity(), LanguageUtil.getAppLocale(App.INSTANCE), true);

        DaggerUserDataComponent.create().inject(this);
        ImageUtil.setCircleImage(R.mipmap.img_default_head, imgHead);
//        noticeImg.setImageResource(isEnglish ? R.mipmap.h_mine_notice_img_en : R.mipmap.h_mine_notice_img);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.requestUserInfo();
            } else {
                userData = null;
                updateStatus(null);
            }
        });
//        noticeSwitch.setFactory(() -> {
//            TextView textView = new TextView(getActivity());
//            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//            textView.setGravity(Gravity.CENTER_VERTICAL);
//            textView.setTextColor(getResources().getColor(R.color.hint));
//            return textView;
//        });

        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {

            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                if (userData != null) {
                    mPresenter.requestUserInfo();
                }else{
                    if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
                        coolRefreshView.setRefreshing(false);
                    }
                }
            }
        });

//        initMenu();
        ClickUtil.click(imgHead, () -> {
            if (mUserInfo == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
//                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

                return;
            }
            startActivity(new Intent(getActivity(), PersonalActivity.class));
        });

        myMoneyCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    tvAsset.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    tvAssetCny.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
//                    usableMoneyTv.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    tvAsset.setTransformationMethod(new AsteriskPasswordTransformationMethod());
                    tvAssetCny.setTransformationMethod(new AsteriskPasswordTransformationMethod());
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            userViewModel.update();
        }
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//
//        if(userData != null){
//            mPresenter.requestUserInfo();
//        }
//    }

    @Override
    public void initData() {
        ClickUtil.click(signImg, () -> {
            if (!isLogin()) {
                return;
            }
            mPresenter.signIn();
        });
        //账户
        ClickUtil.click(tvAccount, () -> {
            if (mUserInfo == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
//                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                return;
            }
            startActivity(new Intent(getActivity(), PersonalActivity.class));
        });

        ClickUtil.click(sqzzssTv, () -> {
            if (!isLogin()) return;
            Bundle bundle = new Bundle();
            bundle.putString(Constans.INTENT_NOTICE_ID, "sqss");
            ARouter.getInstance().build(RConfig.MINE_WEBVIEW).with(bundle).navigation();
        });
        //个人资料
        ClickUtil.click(grzlTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), PersonalActivity.class));
        });
        //安全中心
        ClickUtil.click(aqzxTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
        });
        //资产管理
        ClickUtil.click(zcglTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), AssetManagerActivity.class));
        });
        //提币地址
        ClickUtil.click(tbdzTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), CashAddressListActivity.class));
        });
        //我的推广
        ClickUtil.click(wdtgTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), MyShareActivity.class));
        });
        //关于我们
        ClickUtil.click(gywmTv, () -> {
            startActivity(new Intent(getActivity(), AboutUsActivity.class));
        });
        //设置
        ClickUtil.click(szTv, () -> {
            startActivity(new Intent(getActivity(), GoogleSettingActivity.class));
        });
        //兑换
        ClickUtil.click(exchangeTv, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), ExchangeActivity.class));
        });
        //商家认证
        ClickUtil.click(sjrzTv, () -> {
            if (!isLogin()) {
                return;
            }

            if (!checkIdent(getActivity())) {//是否实名认证
                return;
            }
            if (userData.getConfig().getPayment_password_set()==0) {//是否设置资金密码
                com.sskj.gocoin.utils.ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity218));
                ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
                return;
            }

            if (userData.getIs_shop()==2){
                com.sskj.common.util.ToastUtil.showShort(getString(R.string.my_sjshz));
                return;
            }
            if (userData.getIs_shop()==1){
//                com.sskj.common.util.ToastUtil.showShort(getString(R.string.my_sjyrz));

                TipUtil.getTip(getActivity(), getString(R.string.my_sjshz1), new TipUtil.OnTipSure() {
                    @Override
                    public void onSure() {
                        mPresenter.requestRelieveBusiness();
                    }
                }).show();
                return;
            }
            if (!checkIdentHign(getActivity())) {
                return;
            }
            SellerApplyActivity.start(getActivity());
        });
        //提币
        ClickUtil.click(payOutTv, () -> {
            payOut();
        });
        //充值
        ClickUtil.click(payInTv, () -> {
            payIn();
        });
//        mPresenter.getNotice(1, 20);
    }

    private void payIn() {
        if (!isLogin()) return;
//        RechargeActivity.start(getActivity());
        boolean isPayIn = SPUtil.get("isPayIn",false);
        if(isPayIn){
            ARouter.getInstance().build(RConfig.APP_PAY_IN).navigation();
        }else{
            ARouter.getInstance().build(RConfig.APP_PAY_IN_BEFORE).navigation();
        }

    }

    private void payOut() {
        if (!isLogin()) return;
        if (!checkPwdStatus()) {
            return;
        }
        if (MyAppLication.getRealnameStatus() == 3) {//已实名认证
        } else if (MyAppLication.getRealnameStatus() == 2) {//审核中
            ToastUtil.showShort(App.INSTANCE.getString(R.string.strBaseActivity205));
            return;
        } else if (MyAppLication.getRealnameStatus() == 4) {//被拒绝
            AlertDialog tipDialog = new AlertDialog.Builder(getActivity(), R.style.libDialogStyle)
                    .setTitle(App.INSTANCE.getString(R.string.strBaseActivity208))
                    .setMessage(App.INSTANCE.getString(R.string.mine_high_verify_tip))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strBaseActivity209), (dialog, which) -> {
                        dialog.dismiss();
                        VerifyIdentActivity.start(getActivity());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strBaseActivity211), (dialog, which) -> dialog.dismiss())
                    .create();
            tipDialog.show();
            return;
        } else {
            AlertDialog tipDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(App.INSTANCE.getString(R.string.strBaseActivity208))
                    .setMessage(App.INSTANCE.getString(R.string.mine_high_verify_tip))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strBaseActivity209), (dialog, which) -> {
                        dialog.dismiss();
                        VerifyIdentActivity.start(getActivity());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strBaseActivity211), (dialog, which) -> dialog.dismiss())
                    .create();
            tipDialog.show();
            return;
        }
        ARouter.getInstance().build(RConfig.APP_WITHDRAW_HOME).navigation();
    }

    public boolean checkPwdStatus() {
        if (mUserInfo != null) {
            if (mUserInfo.getConfig().getPayment_password_set()==1) {
                return true;
            } else {
                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.notice)
                        .setMessage(App.INSTANCE.getString(R.string.strTransferActivity206))
                        .setPositiveButton(getResources().getString(R.string.common_sure), (dialog1, which) -> {
                            dialog1.dismiss();
                            startActivity(new Intent(getActivity(), PayPwdSettingActivity.class));
                        }).setNegativeButton(getString(R.string.common_cancel), (dialog12, which) -> dialog12.dismiss()).show();

                return false;
            }
        }
        return false;
    }

    private boolean isLogin() {
        if (userData == null) {
            NoLoginDialog noLoginDialog = new NoLoginDialog(getActivity());
            noLoginDialog.show();
            return false;
        }
        return true;
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void signInSuccess() {
//        if (isEnglish) {
//            signImg.setImageResource(R.mipmap.h_mine_sign_p_en);
//        } else {
//            signImg.setImageResource(R.mipmap.h_mine_sign_p);
//        }
        signImg.setText(App.INSTANCE.getString(R.string.signed));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }

    DecimalFormat mFormat = new DecimalFormat("0.0000");

    public void updateStatus(UserInfo data) {
        mUserInfo = data;
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
        if (data != null) {
            SPUtils.putBean(getContext(), Constants.SP_USER_INFO, data);
            SPUtils.put(getContext(), Constants.SP_REALNAME, data.getName());
            SPUtils.put(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS, data.getAuthentication());
            tvUid.setVisibility(View.VISIBLE);
            if (data.getQd() == 1) {
                signImg.setText(App.INSTANCE.getString(R.string.signed));
//                signImg.setImageResource(isEnglish ? R.mipmap.h_mine_sign_p_en : R.mipmap.h_mine_sign_p);
            } else {
                signImg.setText(App.INSTANCE.getString(R.string.sign));
//                signImg.setImageResource(isEnglish ? R.mipmap.h_mine_sign_en : R.mipmap.h_mine_sign);
            }
            String s = SPUtil.get(Constants.SP_MOBILE, "");
            if (!s.contains("@")) {
                tvAccount.setText(data == null ? App.INSTANCE.getString(R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getHide(s));
            } else {
                tvAccount.setText(data == null ? App.INSTANCE.getString(R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getEmailHide(s));
            }
            tvUid.setText(data == null ? "UID:--" : "UID:" + data.getAccount());
            tvAsset.setText(data == null ? "--" : mFormat.format(data.getWallone()) + "");
            tvAssetCny.setText(data == null ? "--" : NumberUtil.keep2(String.valueOf(data.getCny_money())));
            if (data.getWallone() < data.getMoney1()) {
                ivVip.setVisibility(View.INVISIBLE);
            } else {
                ivVip.setVisibility(View.VISIBLE);
            }
            if (data.getWallone_usdt() >= data.getMoney1()) {
                ivVip.setImageResource(R.mipmap.icon_my_l1);
            }
            if (data.getWallone_usdt() >= data.getMoney2()) {
                ivVip.setImageResource(R.mipmap.icon_my_l2);
            }
            if (data.getWallone_usdt() >= data.getMoney3()) {
                ivVip.setImageResource(R.mipmap.icon_my_l3);
            }
            if (data.getWallone_usdt() >= data.getMoney4()) {
                ivVip.setImageResource(R.mipmap.icon_my_l4);
            }
            if (data.getWallone_usdt() >= data.getMoney5()) {
                ivVip.setImageResource(R.mipmap.icon_my_l5);
            }
//            if (mUserInfo.isIs_shop()) {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.fabimineJavaMineFragment12), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            } else {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.strMineFragment210), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            }
        } else {
            imgHead.setImageResource(R.mipmap.img_default_head);
            tvAccount.setText(App.INSTANCE.getString(R.string.my_login_rigister));
            tvUid.setVisibility(View.GONE);
            signImg.setText(App.INSTANCE.getString(R.string.sign));
            ivVip.setVisibility(View.GONE);
            tvAsset.setText("--");
            tvAssetCny.setText("--");
        }
    }

    public void onRelieveBusinessSuccess() {
        mUserInfo.is_shop = false;
        userData.setIs_shop(2);
        userViewModel.update(userData);
    }
}
